package com.baomidou.ant.controller;

import com.baomidou.ant.common.Result;
import com.baomidou.ant.entity.EndlessInfo;
import com.baomidou.ant.entity.ErrorBook;
import com.baomidou.ant.entity.QuestionInfo;
import com.baomidou.ant.entity.User;
import com.baomidou.ant.service.IEndlessInfoService;
import com.baomidou.ant.service.IErrorBookService;
import com.baomidou.ant.service.IQuestionInfoService;
import com.baomidou.ant.service.IUserService;
import com.baomidou.ant.utils.MyStringUtils;
import com.baomidou.ant.vo.Request.RequestChoiceInfoVo;
import com.baomidou.ant.vo.Request.RequestTimeOutVo;
import com.baomidou.ant.vo.Response.ResponseEndlessQuestionVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.baomidou.ant.utils.RateRandomUtils.produceRateRandomNumber;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2021-03-24
 */
@RestController
@RequestMapping("/endless-info")
public class EndlessInfoController {
    @Autowired
    private IEndlessInfoService endlessInfoService;
    @Autowired
    private IErrorBookService errorBookService;
    @Autowired
    private IQuestionInfoService questionInfoService;
    @Autowired
    private IUserService userService;

    //打开无尽
    @GetMapping("/openGame/{userId}")
    public Result openGame(@PathVariable Integer userId){
        //找到用户纪录
        QueryWrapper<EndlessInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        EndlessInfo endlessInfo=endlessInfoService.getOne(queryWrapper);
        //判断是否是第一次打开游戏
        if(endlessInfo.getNowLevel()>=1){
            //先对比数据是否正常，是否存在恶意退出等行为
            if(endlessInfo.getNowLevel()>=1&& !Objects.equals(endlessInfo.getNowLevel(), endlessInfo.getLastLevel())) {
                //异常退出，错题机会减1
                endlessInfo.setErrorNum(endlessInfo.getErrorNum() - 1);
                endlessInfo.setLastLevel(endlessInfo.getNowLevel());
                //扣血后恢复30s(我们还是比较仁慈的)
                endlessInfo.setNowTime(30);
                endlessInfoService.saveOrUpdate(endlessInfo);
                //判断错题次数是否超出
                if (endlessInfo.getErrorNum() < 0) {
                    //错题机会用完了，重置用户无尽now信息,并退出无尽，从头开始
                    //判断是否破纪录
                    if (endlessInfo.getNowLevel() > endlessInfo.getHighestRecord()) {
                        endlessInfo.setHighestRecord(endlessInfo.getNowLevel() - 1);
                    }
                    //把这次的做过的题目和这次到达的关卡数存下，便于复活卡使用
                    endlessInfo.setLastDone(endlessInfo.getNowDone());
                    endlessInfo.setLastLevel(endlessInfo.getLastLevel() + 1);
                    //重置无尽模式信息
                    endlessInfo.setNowLevel(0);
                    endlessInfo.setNowDone("1");
                    endlessInfo.setErrorNum(3);
                    endlessInfoService.saveOrUpdate(endlessInfo);
                    return Result.getFailure().setMsg("3").setData(endlessInfo);
                } else {
                    //提醒
                    return Result.getFailure().setMsg("2").setData(endlessInfo);
                }
            }
            //没有任何异常情况
            return Result.getSuccess().setMsg("1").setData(endlessInfo);
        }else
            return Result.getSuccess().setMsg("0").setData(endlessInfo);

    }

    //获取题目
    @GetMapping("/getQuestion/{userId}")
    public Result getQuestion(@PathVariable Integer userId){
        //正常出题
        ResponseEndlessQuestionVo vo=endlessInfoService.getQuestion(userId);
        return Result.getSuccess().setData(vo);
    }

    //判断正误
    @PostMapping("/trueOrFalse")
    public Result trueOrFalse(@RequestBody RequestChoiceInfoVo vo){
        //纪录做过的题目
        QueryWrapper<EndlessInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",vo.getUserId());
        EndlessInfo endlessInfo=endlessInfoService.getOne(queryWrapper);
        endlessInfo.setNowDone(MyStringUtils.toString(vo.getQuestionId(),endlessInfo.getNowDone()));

        //无论正确与否，先把时间归为30
        endlessInfo.setNowTime(30);

        //判断正误
        if(endlessInfoService.trueOrFalse(vo)){
            //答对了，关卡加一
            //last关卡
            endlessInfo.setLastLevel(endlessInfo.getNowLevel());
            //下一题,now关卡加1
            endlessInfo.setNowLevel(endlessInfo.getNowLevel()+1);
            //保存修改
            endlessInfoService.saveOrUpdate(endlessInfo);
            return Result.getSuccess().setMsg("1");
        }else{
            //纪录错题本
            QueryWrapper<ErrorBook> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("user_id",vo.getUserId());
            ErrorBook errorBook=errorBookService.getOne(queryWrapper1);
            int[] errorE= MyStringUtils.toInt(errorBook.getEasyEndless());
            int[] errorN= MyStringUtils.toInt(errorBook.getNormalEndless());
            int[] errorH= MyStringUtils.toInt(errorBook.getHardEndless());
            List<Integer> errorEasy = Arrays.stream(errorE).boxed().collect(Collectors.toList());
            List<Integer> errorNormal= Arrays.stream(errorN).boxed().collect(Collectors.toList());
            List<Integer> errorHard= Arrays.stream(errorH).boxed().collect(Collectors.toList());
            //判断题的难度,并判断是否纪录过该数据
            QuestionInfo questionInfo=questionInfoService.getById(vo.getQuestionId());
            if (Objects.equals(questionInfo.getQuestionLevel(), "简单")) {
                if(!errorEasy.contains(questionInfo.getId())){
                    errorBook.setEasyEndless(MyStringUtils.toString(vo.getQuestionId(),errorBook.getEasyEndless()));
                }
            }else if(Objects.equals(questionInfo.getQuestionLevel(), "中等")){
                if(!errorNormal.contains(questionInfo.getId())){
                    errorBook.setNormalEndless(MyStringUtils.toString(vo.getQuestionId(),errorBook.getNormalEndless()));
                }
            }else{
                if(!errorHard.contains(questionInfo.getId())){
                    errorBook.setHardEndless(MyStringUtils.toString(vo.getQuestionId(),errorBook.getHardEndless()));
                }
            }
            //保存
            errorBookService.saveOrUpdate(errorBook);
            //扣除一次错题机会
            endlessInfo.setErrorNum(endlessInfo.getErrorNum()-1);
            endlessInfoService.saveOrUpdate(endlessInfo);
            //判断是否超过规定错题次数
            if(endlessInfo.getErrorNum()<0){
                //超过错题数，则失败
                //判断是否破纪录
                if(endlessInfo.getNowLevel()>endlessInfo.getHighestRecord()){
                    endlessInfo.setHighestRecord(endlessInfo.getNowLevel()-1);
                }
                //把这次的做过的题目和这次到达的关卡数存下，便于复活卡使用
                endlessInfo.setLastDone(endlessInfo.getNowDone());
                endlessInfo.setLastLevel(endlessInfo.getLastLevel()+1);
                //重置无尽模式信息
                endlessInfo.setNowLevel(0);
                endlessInfo.setNowDone("1");
                endlessInfo.setErrorNum(3);
                endlessInfoService.saveOrUpdate(endlessInfo);
                return Result.getFailure().setMsg("0").setData(questionInfo.getRightItem());
            }else
                return Result.getFailure().setMsg("-1").setData(questionInfo.getRightItem());
        }
        //返回1代表正确，返回-1代表错误，返回0代表错误并且达到最高错误次数
    }

    //暂停无尽接口----正常退出
    @PostMapping("/timeOut")
    public Result timeOut(@RequestBody RequestTimeOutVo vo){
        //正常退出保存lastLevel
        QueryWrapper<EndlessInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",vo.getUserId());
        EndlessInfo endlessInfo=endlessInfoService.getOne(queryWrapper);
        endlessInfo.setLastLevel(endlessInfo.getNowLevel());
        //剩余时间保存
        endlessInfo.setNowTime(vo.getNowTime());
        endlessInfoService.saveOrUpdate(endlessInfo);
        return Result.getSuccess().setMsg("已经保存了您的挑战纪录!");
    }

    //无尽宝箱接口
    @GetMapping("/myBox/{userId}")
    public Result myBox(@PathVariable Integer userId){
        //新建一个奖品列表
        List<Object> list=new ArrayList<>();
        //添加奖品
        list.add(500);//0
        list.add(888);//1
        list.add(1000);//2
        list.add(2500);//3
        list.add(5000);//4
        list.add(18888);//5
        //定义分割值
        List<Double> separates = new ArrayList<>();
        separates.add(1.0);
        separates.add(4.0);
        //定义每个分段的概率
        List<Double> percents = new ArrayList<>();
        percents.add(95.0);
        percents.add(4.5);
        percents.add(0.5);
        //得到随机结果
        int result = (int) produceRateRandomNumber(0, 6, separates, percents);
        if(result>5){result=5; }
        result=(int)list.get(result);
        //发放奖励
        User user=userService.getById(userId);
        user.setPoints(user.getPoints()+result);
        userService.saveOrUpdate(user);
        //进入下一关
        EndlessInfo endlessInfo=endlessInfoService.queryByUserId(userId);
        endlessInfo.setNowLevel(endlessInfo.getNowLevel()+1);
        endlessInfoService.saveOrUpdate(endlessInfo);
        return Result.getSuccess().setMsg(String.valueOf(result));
    }


}
